﻿using LanguagePolish.Views;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using LanguagePolish.EntityModel;

namespace LanguagePolish
{
    /// <summary>
    /// Логика взаимодействия для App.xaml
    /// </summary>
    public partial class App : Application
    {
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // Reading the key value
            
            Microsoft.Win32.RegistryKey rkey;
            rkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("TeacherPassword");
            User user = null;
            if (rkey != null)
            {
                object nameObj = rkey.GetValue("Name");
                object passObj = rkey.GetValue("Pass");
                if (nameObj != null && passObj != null)
                {
                    var context = LinksProvider.Model.EntityContext;
                    user = context.Users.FirstOrDefault(x => x.UserLogin == nameObj.ToString() && x.UserPassword == passObj.ToString());
                    if (user != null)
                        LinksProvider.Model.SetUserPermissions(user);
                }
            }
            if (user == null)
            {
                LoginView lw = new LoginView();
                lw.Show();
            }
            else
            {
                MainWindow mw = new MainWindow();
                mw.Show();
            }
        }

        private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.Message +"\nPlease, reload the programm!" );
            this.Shutdown();
        }
    }
}
